<template>
  <div
    class="vc-page vc-page-parts"
    style="position: relative; overflow: hidden"
  >
    <!-- 左侧 - 用户组树 -->
    <div class="part-left">
      <div class="tree-title">
        用户组树
        <el-tooltip content="刷新" placement="bottom">
          <i
            @click="
              filterText = '';
              refreshTree(id);
            "
            class="vc-icon vc-icon-refresh"
          ></i>
        </el-tooltip>
      </div>
      <el-input
        v-if="ugTreeData.length"
        v-model="filterText"
        placeholder="请输入关键字"
        class="vc-search-input"
        size="small"
        clearable
      >
      </el-input>
      <el-tree
        :data="ugTreeData"
        :default-expanded-keys="expandedKeys"
        :empty-text="treeEmptyText"
        :expand-on-click-node="false"
        :props="defaultProps"
        :render-after-expand="true"
        :filter-node-method="filterNode"
        @node-click="ughandleNodeClick"
        @node-collapse="hideRightMenu"
        @node-expand="hideRightMenu"
        class="org-tree"
        highlight-current
        node-key="id"
        ref="ugTree"
      >
        <span
          @mouseenter="point = data"
          @mouseleave="point = null"
          class="slot-scope"
          slot-scope="{ node, data }"
        >
          <i :class="data.icon"></i>
          <span>{{ node.label }}</span>
          <i
            @click.stop="showHandleMenu(data, $event)"
            class="vc-icon vc-icon-more"
            v-if="
              point == data ||
              (!point && data.id == currDicData.id && menuVisible)
            "
          ></i>
        </span>
      </el-tree>
    </div>

    <div class="part-right">
      <el-tabs v-model="tabConfig.activeName">
        <el-tab-pane
          :key="idx"
          :label="item.title"
          :name="item.name"
          class="tabTitle"
          v-for="(item, idx) in tabConfig.items"
        >
          <div>
            <!-- 搜索头 -->
            <searchHeader
              :key="idx"
              :searchConfig="item.searchConfig"
              v-if="tabConfig.activeName === item.name"
            ></searchHeader>
            <!-- 操作按钮 -->
            <div class="vc-btns">
              <el-button
                :class="btn.class ? btn.class : ''"
                :disabled="btn.disabled ? btn.disabled() : false"
                :key="idx"
                :type="btn.type"
                @click="btn.fn"
                size="small"
                v-for="(btn, idx) in item.option"
                >{{ btn.title }}</el-button
              >
            </div>
            <!-- 列表展示 -->
            <div class="vc-table">
              <Tables
                :columns="item.tableConfig.columns"
                :stripe="true"
                @on-selection-change="handleSelectionChange"
                ref="tables"
                v-model="item.tableConfig.tableData"
              />
              <!-- 分页 -->
              <el-pagination
                :current-page.sync="pageConfig.pageNum"
                :page-size="10"
                :total="pageConfig.total"
                @current-change="handleCurrentChange"
                layout="total, prev, pager, next"
              ></el-pagination>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
      <!-- 注释label：选项卡显示的titlename：与选项卡绑定的activeName对应的标识符，表示选项卡的别名
      -->
      <!-- 右键菜单展示 -->
      <ul class="menu-handle-right" id="menuCM" v-show="menuVisible">
        <li @click="addUserGroups">新增同级用户组</li>
        <li @click="addUserGroup">新增下级用户组</li>
        <li @click="editUserGroup">修改用户组</li>
        <li @click="delBtnUserGroup">删除用户组</li>
      </ul>
    </div>

    <!-- 新增用户组 -->
    <add-usergroup
      :addUserGroupDialogVisible="addUserGroupDialogVisible"
      :pid="pid"
      @close="closeAddUserGroupDialog"
      ref="addUserGroupDialog"
    ></add-usergroup>

    <!-- 编辑用户组 -->
    <edit-usergroup
      :editUserGroupDialogVisible="editUserGroupDialogVisible"
      :id="id"
      @close="closeEditUserGroupDialog"
      ref="editUserGroupDialog"
    ></edit-usergroup>

    <!-- 添加角色 -->
    <SelectBox
      ref="selectBox1"
      :allNode="allNode"
      :boxDialogVisible="addRoleDialogVisible"
      :checkedNode="checkedNode"
      :iconConfig="iconConfig"
      :rightKey="'text'"
      :searchConfig="addRoleConfig.search"
      :title="addRoleConfig.title"
      @close="closeAddRoleDialog"
      @save="saveUgroupAndrole"
    />
    <!-- 更改用户 -->
    <SelectBox
      ref="selectBox2"
      :allNode="editUserConfig.allNode"
      :boxDialogVisible="editUserConfig.editVisible"
      :checkedNode="editUserConfig.checked"
      :iconConfig="editUserConfig.iconConfig"
      :listStyle="editUserConfig.listStyle"
      :rightKey="editUserConfig.rightKey"
      :rightKeyQ="editUserConfig.rightKeyQ"
      :searchConfig="editUserConfig.search"
      :title="editUserConfig.title"
      @close="closeEditDialog"
      @save="saveAdduser"
    />
  </div>
</template>

<script>
// 本页面可以弹出四个子页面
import AddUsergroup from './addUsergroup'
import EditUsergroup from './editUsergroup'
import Tables from '_c/tables'
import SelectBox from '_c/selectBox'
import searchHeader from '_c/searchHeader'
import store from '@/store'
const SFGD = store.state.dic.listFormat['sfgd'].map(i => {
  i.title = i.name
  i.key = i.code
  return i
})
const YHLX = store.state.dic.listFormat['yhlx'].map(i => {
  i.title = i.name
  i.key = i.code
  return i
})
const YHZT = store.state.dic.listFormat['yhzt'].map(i => {
  i.title = i.name
  i.key = i.code
  return i
})
export default {
  name: 'ugroups',
  components: {
    AddUsergroup,
    EditUsergroup,
    searchHeader,
    SelectBox,
    Tables
  },
  data () {
    return {
      pid: '',
      iconConfig: {
        parentType: {
          key: 'rgroup',
          icon: 'vc-icon vc-icon-tree-rGroup'
        },
        childrenType: {
          key: 'role',
          icon: 'vc-icon vc-icon-tree-role'
        }
      },
      currDicData: {},
      point: null,
      // 当前多选数组
      selectedIds: [],

      // 左侧树传右表传递发生点击事件的桥梁
      handleNodeClick: 1,

      // 这部分数据与用户右击节点的处理有关
      id: '',

      menuVisible: false,
      editMenuData: {},
      menuInfo: {
        name: '',
        pid: ''
      },
      addUserGroupDialogVisible: false,
      editUserGroupDialogVisible: false,

      // TreeData
      ugTreeData: [],
      ugTreeDataHasTop: [],
      expandedKeys: [],
      defaultProps: {
        id: 'id',
        label: 'name',
        children: 'children',
        isLeaf: 'isLeaf'
      },
      treeEmptyText: ' ',
      filterText: '',
      // tab页配置
      addUserDialogVisible: false, // 新增用户
      addRoleDialogVisible: false, // 新增角色
      checkedNode: [], // 被选中节点
      allNode: [], // 所有节点
      tabConfig: {
        items: [
          {
            name: 'user',
            title: '用户',
            searchConfig: {
              items: [
                {
                  key: 'username',
                  title: '用户名',
                  width: '140px',
                  placeholder: '请输入'
                },
                {
                  key: 'state',
                  title: '用户状态',
                  width: '140px',
                  type: 'select',
                  placeholder: '请选择',
                  groups: YHZT
                },
                {
                  key: 'type',
                  title: '用户类型',
                  width: '140px',
                  type: 'select',
                  placeholder: '请选择',
                  groups: YHLX
                }
              ],
              search: params => {
                this.getTableData()
              },
              reset: () => {
                this.getTableData()
              },
              params: {

              }
            },
            tableConfig: {
              columns: [
                {
                  type: 'selection',
                  width: '50'
                },
                {
                  key: 'index',
                  title: '序号',
                  width: '50',
                  type: 'index'
                },
                {
                  key: 'username',
                  title: '用户名'
                },
                {
                  key: 'nickname',
                  title: '用户昵称'
                },
                {
                  key: 'state',
                  title: '用户状态',
                  formatType: this.formatState
                },
                {
                  key: 'type',
                  title: '用户类型',
                  formatType: this.formatType
                }
              ],
              tableData: []
            },
            option: [
              {
                title: '操作用户',
                class: 'multi-words',
                type: 'primary',
                disabled: () => {
                  return true
                },
                fn: () => {
                  this.openEditUser({
                    data: {
                      ugroupId: this.id
                    }
                  })
                }
              },
              {
                title: '删除',
                type: '',
                disabled: () => {
                  return this.selectedIds.length === 0
                },
                fn: () => {
                  this.$confirmBox(this.deleteModel)
                }
              }
            ]
          },
          {
            name: 'role',
            title: '角色',
            searchConfig: {
              items: [
                {
                  key: 'name',
                  title: '角色名称',
                  width: '140px',
                  placeholder: '请输入'
                }
              ],
              search: params => {
                this.getTableData()
              },
              reset: () => {
                this.getTableData()
              },
              params: {

              }
            },
            tableConfig: {
              columns: [
                {
                  type: 'selection',
                  width: '50'
                },
                {
                  key: 'index',
                  title: '序号',
                  width: '50',
                  type: 'index'
                },
                {
                  key: 'code',
                  title: '编码'
                },
                {
                  key: 'name',
                  title: '角色名称'
                },
                {
                  key: 'descr',
                  title: '角色描述'
                }
              ],
              tableData: []
            },
            option: [
              {
                title: '操作角色',
                class: 'multi-words',
                type: 'primary',
                fn: () => {
                  this.openAddRole({ data: { descendant: '1' } })
                }
              },
              {
                title: '删除',
                disabled: () => {
                  return this.selectedIds.length === 0
                },
                type: '',
                fn: () => {
                  this.$confirmBox(this.deleteRole)
                }
              }
            ]
          }
        ],
        activeName: 'user'
      },
      editUserConfig: {
        rightKey: 'text',
        rightKeyQ: 'nickname',
        editVisible: false,
        title: '选择用户',
        listStyle: 'tree',
        iconConfig: {
          parentType: {
            key: 'org',
            icon: 'vc-icon vc-icon-tree-org'
          },
          childrenType: {
            key: 'user',
            icon: 'vc-icon vc-icon-tree-user'
          }
        },
        search: {
          title: '请输入',
          patch: 'getUserByUsername',
          key: 'nickname',
          params: {}
        },
        allNode: [],
        checked: []
      },
      addRoleConfig: {
        rightKey: 'text',
        editVisible: false,
        title: '选择角色',
        listStyle: 'tree',
        search: {
          title: '请输入',
          patch: 'getRoleByUserName',
          key: 'name',
          params: {}
        },
        allNode: [],
        checked: []
      },
      // 分页设置
      pageConfig: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
    }
  },
  computed: {
    userStatus () {
      return this.$store.state.dic.listFormat['yhzt']
    }
  },
  watch: {
    'tabConfig.activeName': {
      handler (newName, oldName) {
        this.pageConfig.pageNum = 1
        this.getTableData()
      }
    },
    filterText (val) {
      this.$refs.ugTree.filter(this.GLOBAL.filter.filterSpace(val))
    }
  },
  mounted () {
    $('.org-tree').scroll(() => {
      this.hideRightMenu()
    })
    document.addEventListener('mousedown', this.mousedown)
    this.ini()
  },
  beforeDestroy () {
    document.removeEventListener('mousedown', this.mousedown)
  },
  methods: {
    /**
     * deleteRole
     */
    deleteRole () {
      this.$api
        .deleteUgRolesByUgidAndRoleids({
          data: {
            roleIds: this.selectedIds,
            ugroupId: this.id
          }
        })
        .then(res => {
          if (res.success) {
            this.$message.success('删除成功')
            this.getTableData()
          } else {
            this.getTableData()
          }
        })
    },
    /**
     * 显示树节点操作菜单
     */
    showHandleMenu (data, ev) {
      this.rightClick(data)
      this.currDicData = Object.assign({}, data)
      let $menu = $('#menuCM')
      if (ev.clientY + $menu.outerWidth() < innerHeight) {
        $menu.css('top', ev.clientY + 'px')
        $menu.css('bottom', 'auto')
      } else {
        $menu.css('top', 'auto')
        $menu.css('bottom', innerHeight - ev.clientY + 'px')
      }
      $menu.css('left', ev.clientX + 'px')
      this.menuVisible = true
    },
    /**
     * 鼠标点击触发事件
     */
    mousedown (ev) {
      if (!this.menuVisible) return
      let pid = ev.target.parentElement.id
      if (pid !== 'menuCM') return this.hideRightMenu()
      if (ev.button !== 0) return
      ev.target.click()
      this.hideRightMenu()
    },
    /**
     * 隐藏右键菜单
     */
    hideRightMenu () {
      this.menuVisible = false
    },
    /*
      删除模块
    */
    deleteModel () {
      this.$api
        .removeByUgroupIdAndRoleIds({
          data: {
            userIds: this.selectedIds,
            ugroupId: this.id
          }
        })
        .then(res => {
          if (res.success) {
            this.$message.success('删除成功')
            this.getTableData()
          } else {
            this.getTableData()
          }
        })
    },
    /**
     * 保存y用户
     */
    saveAdduser (add, deleteList, flage) {
      this.$api
        .removeAndAddUser({
          data: {
            addUserIds: add,
            removeUserIds: deleteList,
            ugroupId: this.id
          }
        })
        .then(res => {
          flage = false
          if (res.success) {
            this.$notifyBox('操作用户成功', 'success')
            this.editUserConfig.editVisible = false
            this.getTableData()
            return
          }
          this.$refs.selectBox2.closeDisabled()
        }).catch(err => {
          this.$refs.selectBox2.closeDisabled()
        })
    },
    /*
      获取用户
    */
    searchUser () { },
    /**
     * 保存角色与用户组
     */
    saveUgroupAndrole (add, deleteList) {
      this.$api
        .addRgroupAndRole({
          data: {
            addRoleIds: add,
            removeRoleIds: deleteList,
            ugroupId: this.id
          }
        })
        .then(res => {
          if (res.success) {
            this.$notifyBox('操作角色成功', 'success')
            this.addRoleDialogVisible = false
            this.getTableData()
            return
          }
          this.$refs.selectBox1.closeDisabled()
        }).catch(err => {
          this.$refs.selectBox1.closeDisabled()
        })
    },
    /**
     * 复选框勾选记录勾选的值
     */
    handleSelectionChange (val) {
      this.selectedIds = this.GLOBAL.array.selectOneKey(val, 'id')
    },
    /**
     * 树节点右键点击时的回调
     */
    rightClick (data) {
      this.editMenuData = data
    },
    /**
     * 新增下级用户组
     */
    addUserGroup () {
      this.pid = this.editMenuData.id
      this.$nextTick(() => {
        this.addUserGroupDialogVisible = true
      })
    },
    /*
      新增同级用户组
    */
    addUserGroups () {
      this.pid = this.editMenuData.pid
      this.$nextTick(() => {
        this.addUserGroupDialogVisible = true
      })
    },
    /**
     * 编辑用户组
     */
    editUserGroup () {
      this.$nextTick(() => {
        this.editUserGroupDialogVisible = true
      })
    },
    /**
     * 删除用户组点击事件
     */
    delBtnUserGroup () {
      this.$confirmBox(this.delUserGroup)
    },
    /**
     * 删除用户组
     */
    delUserGroup () {
      this.$api
        .deleteUserGroupById({
          // 删除树中节点
          data: {
            id: this.editMenuData.id
          }
        })
        .then(res => {
          this.refreshTree(this.editMenuData.id, 1) // 刷新树 删除时 如果删除的节点是cur key，回退cur key。否则保持。
          if (res.success) {
            this.$notifyBox('删除成功', 'success')
          }
        })
    },
    /**
     * '新增用户组'弹出框关闭事件
     */
    closeAddUserGroupDialog (val) {
      this.addUserGroupDialogVisible = false
      val && this.refreshTree(this.id)
    },
    /**
     * '新增用户'弹出框关闭事件
     */
    closeAddUserDialog (val) {
      this.addUserDialogVisible = false
      this.refresh()
    },
    closeEditDialog () {
      this.editUserConfig.editVisible = false
    },
    /*
      '新增角色'弹出框关闭
    */
    closeAddRoleDialog (val) {
      this.addRoleDialogVisible = false
      this.allNode = []
      // this.refresh()
    },
    /**
     * '编辑'弹出框关闭事件
     */
    closeEditUserGroupDialog (val) {
      this.editUserGroupDialogVisible = false

      this.refreshTree(this.editMenuData.id)
    },

    ini () {
      this.refreshTree()
    },

    /**
     * 刷新树数据
     */
    refreshTree (checkedKey, del) {
      this.tabConfig.items[0].option[0].disabled = () => { return true }
      // 先保存树的刷新状态。
      let expandedKeys = this.$refs.ugTree.store
        ._getAllNodes()
        .filter(item => item.expanded === true)
        .map(item => item.key)

      expandedKeys.push(checkedKey)

      // 然后调用api刷新树的数据。
      this.$api.getAllUsergroup_api().then(res => {
        if (!res.success) {
          return
        }
        res.data = res.data || []
        this.treeEmptyText = this.GLOBAL.QUERY.EMPTY_TEXT
        res.data.forEach(i => {
          i.icon = 'vc-icon vc-icon-tree-uGroup'
        })
        this.ugTreeDataHasTop = this.GLOBAL.array.transToTreeData(res.data) // 查询用户组时，没有带固定数值

        this.ugTreeData = this.ugTreeDataHasTop
        // 异步回调里需要分类处理右击各个子节点的后续处理——>比如设置cur key。展开、高亮、右侧列表展示等。
        this.$nextTick(() => {
          if (!checkedKey) {
            this.ughandleNodeClick(this.ugTreeData[0])
            this.expandedKeys.push(this.ugTreeData[0].id) // 初始化时的场景，展开第一个节点。
            return
          }

          // 剩余的场景包括新增、编辑、删除树节点。

          this.expandedKeys = expandedKeys // 先恢复展开状态

          if (del === 1 && this.id === checkedKey) {
            // 如果删除了点选的树节点。保持展开树状态，并回跳到首节点。
            this.ughandleNodeClick(this.ugTreeData[0])
            return
          } else if (del === 1) {
            // 删除的节点不是高亮的节点，恢复cur key后返回。
            this.$refs.ugTree.setCurrentKey(this.id)
            return
          }

          // 其余场景设置右击的节点为高亮
          this.$refs.ugTree.setCurrentKey(checkedKey)

          this.id = checkedKey
        })
      })
    },
    formatState (row) {
      return row.state
        ? this.$store.state.dic.mapFormat['yhzt'][row.state]
        : ' '
    },
    formatType (row) {
      return row.type ? this.$store.state.dic.mapFormat['yhlx'][row.type] : ' '
    },
    /**
     * 用户组树节点被点击时的回调
     */
    async ughandleNodeClick (data) {
      this.$refs.ugTree.setCurrentKey(data.id)
      this.id = data.id
      this.getTableData()
      let res = await this.$api.hasRole({
        data: {
          ugroupId: this.id
        }
      })
      this.tabConfig.items[0].option[0].disabled = () => { return !res.data }
      this.$forceUpdate()
    },
    /* 获取表格 */
    getTableData () {
      switch (this.tabConfig.activeName) {
        case 'user':
          this.getUsersByUgroupId()
          break
        case 'role':
          this.getRolesByUgroupId()
      }
    },
    /**
     * 获取用户 user数据
     */
    getUsersByUgroupId (
      id = this.id,
      pageNum = this.pageConfig.pageNum,
      pageSize = this.pageConfig.pageSize
    ) {
      let item = this.tabConfig.items.filter(i => i.name === 'user')[0]

      this.$api
        .getUsersByUgroupId({
          data: {
            id: id,
            pageNum: pageNum,
            pageSize: pageSize,
            params: item.searchConfig.params
          }
        })
        .then(res => {
          if (res.success) {
            if (res.data.records.length !== 0) {
              item.tableConfig.tableData = res.data.records
              this.pageConfig.total = res.data.total
              this.pageConfig.pageNum = res.data.current
            } else if (this.pageConfig.pageNum > 1) {
              this.pageConfig.pageNum--
              this.getTableData()
            } else {
              this.pageConfig.pageNum = 1
              item.tableConfig.tableData = []
            }
          }
        })

      // this.getUsersByUgroupIdNotPage()
    },
    /**
     * 获取角色 role 数据
     */
    getRolesByUgroupId (
      id = this.id,
      pageNum = this.pageConfig.pageNum,
      pageSize = this.pageConfig.pageSize
    ) {
      let item = this.tabConfig.items.filter(i => i.name === 'role')[0]
      this.$api
        .getRolesByUgroupId({
          data: {
            id: id,
            pageNum: pageNum,
            pageSize: pageSize,
            params: item.searchConfig.params
          }
        })
        .then(res => {
          if (res.success) {
            if (res.data.records.length !== 0) {
              item.tableConfig.tableData = res.data.records
              this.pageConfig.total = res.data.total
              this.pageConfig.pageNum = res.data.current
            } else if (this.pageConfig.pageNum > 1) {
              this.pageConfig.pageNum--
              this.getTableData()
            } else {
              this.pageConfig.pageNum = 1
              item.tableConfig.tableData = []
            }
          }
        })

      // this.getRolesByUgroupIdNotPage()
    },
    // 获取已选中节点数据
    getCheckedData (checkedNode) {
      this.checkedNode = checkedNode
    },
    /**
     * 点击操作角色时获取所有角色
     *
     */
    openAddRole (p) {
      this.$api.getCurrRole(p).then(res => {
        this.allNode = res.data
        this.$api
          .getCheckedRolesByUgroupId({
            data: {
              ugroupId: this.id
            }
          })
          .then(res => {
            if (res.data) {
              this.checkedNode = res.data
            } else {
              this.checkedNode = []
            }
            this.addRoleDialogVisible = true
          })
      })
    },
    /**
     * 点击操作用户获取所有拥有用户
     */
    openEditUser (p) {
      this.$api.getUsersByUgroupIdNotPage(p).then(res => {
        if (res.data) {
          this.editUserConfig.checked = res.data
        } else {
          this.editUserConfig.checked = []
        }
        this.$api.getTreeData().then(call => {
          if (!call.success) {
            return
          }
          call.data[0] = res.data[0] || []
          call.data[1] = res.data[1] || []
          call.data[1].forEach(i => {
            if (!i.pid && i.type === 'user') {
              i.pid = 'other'
            }
          })
          this.editUserConfig.allNode = call.data[0].concat(
            call.data[1]
          )
          this.editUserConfig.allNode.push({
            id: 'other',
            text: '其他',
            children: [],
            type: 'org',
            pid: null
          })
          this.editUserConfig.editVisible = true
        })
      })
    },
    /**
     * 点击页数
     */
    handleCurrentChange (val) {
      this.pageConfig.pageNum = val
      this.getTableData() // 分table页。点击分页控件时的操作。
    },
    /**
     * 对树节点进行筛选
     */
    filterNode (value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    }
  }
}
</script>
